﻿using System.Activities.Statements;
using System.Collections.Generic;
using Headsight.BPMN2WF.BPMN.Model;

namespace Headsight.BPMN2WF.Transformation.Transformers
{
    internal class BPMN2WFTransformationSequence : IBPMN2WFTransformation
    {
        public BPMNTransformationResult Transform(IBPMN2WFTransformationContext ctx, BPMNFlowNode flowNode)
        {
            // should be save enough... if this cast is not possible then this implementation
            // has been wrongly configured for application within the overall transformation process...
            var processBlock = (BPMNFlowNodesBlock)flowNode;

            var result = new Sequence();

            // NodeIn is the tExclusiveGateway
            var bpmnTransformator = ctx.BPMN2WFTransformations.Get(processBlock.FlowNodeIn);
            
            result.Activities.Add(bpmnTransformator.Transform(ctx, processBlock.FlowNodeIn).Result);
            TransformRecursive(result, ctx, processBlock, processBlock.GetNextNodesInFlowFrom(processBlock.FlowNodeIn));

            return new BPMNTransformationResult(result, result.Activities[0], result.Activities[result.Activities.Count - 1]);
        }

        private static void TransformRecursive(Sequence sequence, IBPMN2WFTransformationContext ctx, BPMNFlowNodesBlock processBlock, IEnumerable<BPMNFlowNode> flowNodes)
        {
            foreach (var each in flowNodes)
            {
                var result = ctx.BPMN2WFTransformations.Get(each).Transform(ctx, each);

                // simplify...?!
                sequence.Activities.Add(result.Result);

                TransformRecursive(sequence, ctx, processBlock, processBlock.GetNextNodesInFlowFrom(each));
            }
        }

    }
}
